<template>
  <el-card>
    <el-button type="primary" @click="showAddModal">添加权限</el-button>
    <el-button type="primary" @click="showUploadModal">数据导入</el-button>
    <el-button type="primary" @click="exportData">数据导出</el-button>
    <el-table
        :data="permissionList"      style="width: 100%"
        row-key="permissionId"
        border
    >
      <el-table-column prop="permissionName" label="权限名称"></el-table-column>
      <el-table-column prop="icon" label="图标" width="100">
        <template #default="scope">
          <i :class="scope.row.icon"></i>
        </template>
      </el-table-column>
      <el-table-column prop="permissionCode" label="权限代码"></el-table-column>
      <el-table-column prop="permissionType" label="权限类型">
        <template #default="scope">
          {{ scope.row.permissionType === '0' ? '目录' : scope.row.permissionType === '1' ? '菜单' : '按钮' }}
        </template>
      </el-table-column>
      <el-table-column prop="path" label="路径" ></el-table-column>
      <el-table-column align="center" prop="status" label="状态">
        <template #default="{ row }">
          <el-radio-group v-model="row.status" is-button size="small" @change="updateDictionaryStatus(row)">
            <el-radio-button :label="i.label" :value="i.value" v-for="i in options"/>
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间"></el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="showEditModal(row)">编辑</el-button>
          <el-popconfirm title="确认删除?" @confirm="deletePermission(row.permissionId)">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 添加权限模态框 -->
  <el-dialog v-model="addDialogVisible" title="添加权限">
    <el-form ref="addFormRef" :model="addFormData" label-width="80px" :rules="rules">
      <el-form-item label="类型" prop="permissionType">
        <el-radio-group v-model="addFormData.permissionType" is-button>
          <el-radio-button label="目录" value="0" />
          <el-radio-button label="菜单" value="1" />
          <el-radio-button label="按钮" value="2" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="父级" prop="parentId" v-if="addFormData.permissionType==='1' || addFormData.permissionType==='2'">
        <el-cascader v-model="addPermissionType" :props="{label: 'permissionName',value: 'permissionId'}" :options="addFormData.permissionType==='1'?contentList:menuList" :show-all-levels="false" />
      </el-form-item>
      <el-form-item label="名称" prop="permissionName">
        <el-input v-model="addFormData.permissionName"></el-input>
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <el-input v-model="addFormData.icon"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sortOrder">
        <el-input-number v-model="addFormData.sortOrder" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="代码" prop="permissionCode">
        <el-input v-model="addFormData.permissionCode"></el-input>
      </el-form-item>
      <el-form-item label="路径" prop="path">
        <el-input v-model="addFormData.path"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="addFormData.status" placeholder="请选择状态">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addPermission(addFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑权限模态框 -->
  <el-dialog v-model="editDialogVisible" title="编辑权限">
    <el-form ref="editFormRef" :model="editFormData" label-width="80px" :rules="rules">
      <el-form-item label="权限名称" prop="permissionName">
        <el-input v-model="editFormData.permissionName"></el-input>
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <el-input v-model="editFormData.icon"></el-input>
      </el-form-item>
      <el-form-item label="权限名称" prop="permissionType">
        <el-input v-model="editFormData.permissionType"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sortOrder">
        <el-input-number v-model="editFormData.sortOrder" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="权限代码" prop="permissionCode">
        <el-input v-model="editFormData.permissionCode"></el-input>
      </el-form-item>
      <el-form-item label="路径" prop="path">
        <el-input v-model="editFormData.path"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="editFormData.status" placeholder="请选择状态">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePermission(editFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { fetchPermissionTree, postPermission, putPermission, delPermission, batchDelPermission, exportPermissionData } from "@/api/PermissionApi.ts";
import type { ElMessage, UploadProps, FormInstance, FormRules } from 'element-plus';
import { UploadFilled } from "@element-plus/icons-vue";
import {Permission} from "@/api/type/model.ts";


const permissionList: Permission[] = ref([]);
const menuList: Permission[] = ref([]);
const contentList: Permission[] = ref([]);
const addPermissionType = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const addDialogVisible = ref(false);
const addKeyValueDialogVisible = ref(false);
const editDialogVisible = ref(false);
let addFormData: Permission = reactive({});
let editFormData: Permission = reactive({});
const multipleSelection = ref<Permission[]>([]);
const uploadDialogVisible = ref(false);
const uploadURL = ref(import.meta.env.VITE_APP_BASE_FILE_API);

const addFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  name: [
    { required: true, trigger: 'blur' },
    { min: 1, max: 100, message: '字数必须为 1 到 100', trigger: 'blur', informType: 'warning' },
  ],
  type: [
    { required: true, trigger: 'blur' },
    { min: 1, max: 100, message: '字数必须为 1 到 100', trigger: 'blur', informType: 'warning' },
  ]
});

const formInline: Permission = reactive({
  parentId: 0
});

const during = ref([])

const options = ref([
  { value: '1', label: '正常' },
  { value: '0', label: '禁用' }
]);

const fetchPermission = async () => {
  const response = await fetchPermissionTree();
  permissionList.value = JSON.parse(JSON.stringify(response.data))
  contentList.value = JSON.parse(JSON.stringify(response.data))
  menuList.value = JSON.parse(JSON.stringify(response.data))
  contentList.value.forEach(item => {
    item.children=[]
  })
  menuList.value.forEach(item=>{
    item.children.forEach(i=>{i.children=[]})
  })
};

const addPermission = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }
    addFormData.parentId=addPermissionType.value[0]
    const res = await postPermission(addFormData);
    if (res.code === 200){
      addDialogVisible.value = false;
      addKeyValueDialogVisible.value = false;
      await fetchPermission();
    }
  });
};

const cancelUpdatePermission = () => {
  editDialogVisible.value = false;
  fetchPermission();
};

const updatePermission = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }
    await putPermission(editFormData);
    editDialogVisible.value = false;
    await fetchPermission();
  });
};

const updatePermissionStatus = async (permission: Permission) => {
  await putPermission(permission);
  editDialogVisible.value = false
  await fetchPermission();
};

const deletePermission = async (id: number) => {
  await delPermission(id);
  await fetchPermission();
};

const showAddModal = () => {
  addFormRef.value?.resetFields();
  addDialogVisible.value = true;
};

const showAddKeyValueModal = () =>{
  addFormRef.value?.resetFields();
  addKeyValueDialogVisible.value = true;
}

const showEditModal = async (row: any) => {
  editFormData = row;
  editFormRef.value?.clearValidate();
  editDialogVisible.value = true;
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  fetchPermission();
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  fetchPermission();
};

// 数据导入
const showUploadModal = () => {
  uploadDialogVisible.value = true;
}
const handleUploadSuccess: UploadProps['onSuccess'] = () => {
  ElMessage.success("导入成功");
  uploadDialogVisible.value = false;
  fetchPermission();
}

// 导出数据
const exportData = async () => {
  const res = await exportPermissionData();
  const blob = new Blob([res.data]);
  let url = window.URL.createObjectURL(blob);
  let link = document.createElement("a");
  link.href = url;
  link.setAttribute('download', formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss') + ".csv");
  document.body.appendChild(link);
  link.click();
}

const load = (
    row: Permission,
    treeNode: unknown,
    resolve: (date: Permission[]) => void
) => {
  setTimeout(() => {
    resolve([
      {
        id: 31,
        date: '2016-05-01',
        name: 'wangxiaohu',
      },
      {
        id: 32,
        date: '2016-05-01',
        name: 'wangxiaohu',
      },
    ])
  }, 1000)
}


fetchPermission();


</script>

<style scoped>
.el-card {
  margin-top: 20px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 0 #ffffff;
  outline: 0;
}
</style>

